// src/utils/httpClient.ts
import axios from 'axios';

// 配置类型定义
interface SecurityHeaders {
    Authorization: string;
    'X-Server-Param': string;
    'X-CurTime': string;
    'X-CheckSum': string;
}

// 创建带基础配置的 Axios 实例
const apiClient = axios.create({
    baseURL: window.config.API_BASE_URL,
    timeout: 10000,
    headers: {
        'Content-Type': 'application/json'
    }
});

const generateSecurityHeaders = (): SecurityHeaders => {
    // 获取当前时间戳
    const curtime = Math.floor(Date.now() / 1000);

    // 构造headers对象
    const headers = {
        'X-Server-Param': 'eyJhcHBpZCI6ICJkc2p5eWJhaSIsICJjc2lkIjogImRzanl5YmFpd3RjaGF0YmlybXMwMDAwMDAwMDAwMDAwYTlkODM0N2I2ZDgyNDJmNTlkNDU1OGQxNTg4NzM0YjUifQ',
        'X-CurTime': curtime.toString(),
        'X-CheckSum': '46c535a98c79c227f707ebe4602763f8',
        Authorization: 'Bearer ZTNkNjY5YTUzNDZjMjUzMzpjaGF0YmlA5rWL6K-V6LSm5Y-3OnVhdDo0MmVhMDMxOTJhNjM4YmNk'
    };

    return headers;
};

// 请求拦截器（统一添加头部）
apiClient.interceptors.request.use((config: any) => {
    // 合并安全头部
    config.headers = {
        ...config.headers,
        ...generateSecurityHeaders()
    };

    // 特殊接口处理示例
    if (config.url?.includes('/upload')) {
        config.headers['Content-Type'] = 'multipart/form-data';
    }

    return config;
});

// 响应拦截器（统一错误处理）
apiClient.interceptors.response.use(
    response => response.data,
    error => {
        console.error('API Error:', error.response?.status);
        return Promise.reject(error);
    }
);

// 封装常用方法
export const http = {
    get: <T>(url: string) => apiClient.get<T>(url),
    post: <T>(url: string, data?: any) => apiClient.post<T>(url, data),
    put: <T>(url: string, data?: any) => apiClient.put<T>(url, data),
    delete: <T>(url: string) => apiClient.delete<T>(url)
};
